package com.jk.service.impl;

import com.github.pagehelper.PageHelper;
import com.jk.bean.*;
import com.jk.mapper.UserMapper;
import com.jk.service.UserService;
import com.jk.utils.FileUtil;
import com.jk.utils.MyException;
import com.jk.utils.ReceivePage;
import com.jk.utils.SendPage;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public SendPage queryUser(User user, ReceivePage rp) {
        List<User> list = new ArrayList<User>();
        List<User> data = new ArrayList<User>();
        if(user.getState()==0){
             list = userMapper.queryUser(user);

            PageHelper.startPage(rp.getPage(), rp.getRows());
             data = userMapper.queryUser(user);
        }else {
            list = userMapper.queryUser1();

            PageHelper.startPage(rp.getPage(), rp.getRows());
             data = userMapper.queryUser1();
        }


        return new SendPage(list.size(), data);
    }

    @Override
    public void delUser(String ids) {
        userMapper.delUser(ids);
    }

    @Override
    public User queryUserById(String id) {
        return userMapper.queryUserById(id);
    }

    @Override
    public void updateUser(User user, HttpServletRequest request, MultipartFile file) {

        if (file != null && file.getSize() > 0) {
            String upload = FileUtil.upload(file, request);
            user.setImg(upload);
        }

        userMapper.updateUser(user);
    }

    @Override
    public SendPage queryStaff(ReceivePage receivePage) {
        List<Staff> list = userMapper.queryStaff();

        PageHelper.startPage(receivePage.getPage(), receivePage.getRows());
        List<Staff> data = userMapper.queryStaff();

        return new SendPage(list.size(), data);
    }

    @Override
    public void delStaff(String ids) {
        userMapper.delStaff(ids);
    }

    @Override
    public void addStaff(Staff staff) {

        if (staff.getStaffId() == null) {
            userMapper.addStaff(staff);
        } else {
            userMapper.updateStaff(staff);
        }
    }

    @Override
    public Staff queryStaffById(String id) {
        return userMapper.queryStaffById(id);
    }

    @Override
    public void updateUserState(User user) {
        userMapper.updateUserState(user);
    }

    @Override
    public List<Staff> queryPoi(String ids) {
        return userMapper.queryPoi(ids);
    }


    //poi导入msql
    @Override
    public boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        List<Staff> userList = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        Staff user;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            user = new Staff();

            String staffName = row.getCell(1).getStringCellValue();
            if (staffName == null || staffName.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,账号未填写)");
            }
            String staffPwd = row.getCell(2).getStringCellValue();
            if (staffPwd == null) {
                throw new MyException("导入失败(第" + (r + 1) + "行,不存在此单位或单位未填写)");
            }

            user.setStaffName(staffName);
            user.setStaffPwd(staffPwd);

            userList.add(user);
        }
        for (Staff userResord : userList) {
            String name = userResord.getStaffName();
            int cnt = userMapper.selectByName(name);

            if (!name.equals("账号")) {
                if (cnt == 0) {
                    userMapper.addStaff(userResord);
                    System.out.println(" 插入 " + userResord);
                } else {
                    userMapper.updateUserByName(userResord);
                    System.out.println(" 更新 " + userResord);
                }

            }

        }
        return notNull;
    }


    //poi导入mongodb
    @Override
    public boolean importMongo(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        List<Log> logList = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        Log log;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            log = new Log();

            String userAccout = row.getCell(1).getStringCellValue();
            if (userAccout == null || userAccout.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,账号未填写)");
            }
            String addTime = row.getCell(2).getStringCellValue();
            if (addTime == null || userAccout.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,不存在此单位或单位未填写)");
            }
            String name = row.getCell(3).getStringCellValue();
            if (name == null || name.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,不存在此单位或单位未填写)");
            }
            String version = row.getCell(4).getStringCellValue();
            if (version == null || version.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,不存在此单位或单位未填写)");
            }
            String phone = row.getCell(5).getStringCellValue();
            if (phone == null || phone.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,不存在此单位或单位未填写)");
            }

            if(!addTime.equals("登录时间")){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                log.setUserAccout(userAccout);
                log.setAddTime(sdf.parse(addTime));
                log.setName(name);
                log.setVersion(version);
                log.setPhone(phone);

                logList.add(log);

            }

        }
        for (Log userResord : logList) {

            mongoTemplate.save(userResord);
            System.out.println(" 插入 " + userResord);

        }


        return notNull;
    }

    @Override
    public SendPage queryYuLeSP(ReceivePage page) {

        List<TuTu>  list=userMapper.queryYuLeSP();

        PageHelper.startPage(page.getPage(),page.getRows());
        List<TuTu>  data=userMapper.queryYuLeSP();

        SendPage  sp=new  SendPage(list.size(),data);
        return sp;
    }

    @Override
    public void tongGuo(String ids) {
        userMapper.tongGuo(ids);
    }

    @Override
    public void JuJueTuiJian(String ids) {
        userMapper.JuJueTuiJian(ids);
    }

    @Override
    public SendPage queryGuangGaoInfo(ReceivePage page) {
        List<GuangGao>  list=userMapper.queryGuangGaoInfo();

        PageHelper.startPage(page.getPage(),page.getRows());
        List<GuangGao>  data=userMapper.queryGuangGaoInfo();

        SendPage  sp=new  SendPage(list.size(),data);
        return sp;
    }

    @Override
    public void updateGGW(GuangGao gg) {
        userMapper.updateGGW(gg);
    }

    @Override
    public List<User> queryUserPoi(String ids) {
        return userMapper.queryUserPoi(ids);
    }

    @Override
    public void updateStatus(User user) {
        userMapper.updateStatus(user);
    }

    @Override
    public SendPage queryDKS(ReceivePage page) {
        List<Bks>   list=userMapper.queryDKS();

        PageHelper.startPage(page.getPage(),page.getRows());
        List<Bks>   data=userMapper.queryDKS();
        SendPage  sp=new   SendPage(list.size(),data);
        return sp;
    }

    @Override
    public String deleteDKS(String ids) {
        userMapper.deleteDKS(ids);
        return "";
    }


    @Override
    public List<Emp> exportExcel() {
        return userMapper.exportExcel();
    }

}
